package yur.wedding.modules.sys.service.impl;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;


import org.springframework.transaction.annotation.Transactional;
import yur.wedding.common.utils.Constant;
import yur.wedding.common.utils.Query;

import yur.wedding.modules.sys.dao.SysRoleDao;
import yur.wedding.modules.sys.entity.SysDeptEntity;
import yur.wedding.modules.sys.entity.SysRoleEntity;
import yur.wedding.modules.sys.entity.SysUserEntity;
import yur.wedding.modules.sys.service.*;
import yur.wedding.utils.PageUtils;

import javax.annotation.Resource;


@Service("sysRoleService")
public class SysRoleServiceImpl extends ServiceImpl<SysRoleDao, SysRoleEntity> implements SysRoleService {
    @Resource
    SysRoleDeptService sysRoleDeptService;

    @Resource
    SysRoleMenuService sysRoleMenuService;

    @Resource
    SysDeptService sysDeptService;

    @Resource
    SysUserService sysUserService;

    @Autowired
    private SysRoleDoorService sysRoleDoorService;
    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String roleName = (String) params.get("role_name");
        IPage<SysRoleEntity> page = this.page(
                new Query<SysRoleEntity>().getPage(params),
                new QueryWrapper<SysRoleEntity>()
                        .eq(StringUtils.isNotBlank(roleName), "role_name", roleName)
                //   .apply(params.get(Constant.SQL_FILTER) != null, (String) params.get(Constant.SQL_FILTER))
        );

        //同步获取 部门id
        for (SysRoleEntity sysRoleEntity : page.getRecords()) {
            SysDeptEntity deptEntity = sysDeptService.getById(sysRoleEntity.getDeptId());
            if (deptEntity != null) {
                sysRoleEntity.setDeptName(deptEntity.getName());
            }
        }
        return new PageUtils(page);
    }

    /**
     * 添加角色同步 添加权限
     *
     * @param sysRole
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveRole(SysRoleEntity sysRole) {


        String firstChar = toFirstChar(sysRole.getRoleName());

        sysRole.setCreateTime(new Date());
        sysRole.setPinYinRoleName(firstChar);
        this.save(sysRole);
        System.out.println("添加角色成功");
        //同步添加数据权限
        sysRoleDeptService.saveOrUpdate(sysRole.getRoleId(), sysRole.getDeptIdList());
        //同步添加菜单权限
        System.out.println("添加数据权限成功");
        sysRoleMenuService.saveOrUpdate(sysRole.getRoleId(), sysRole.getMenuIdList());
        System.out.println("添加菜单权限成功");

        sysRoleDoorService.saveOrUpdate(sysRole.getRoleId(), sysRole.getDoorIdList());
        System.out.println("添加门户权限成功");
    }

    /**
     * 同步修改角色  与角色的权限
     *
     * @param sysRole
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateRole(SysRoleEntity sysRole) {

        this.updateById(sysRole);
        System.out.println("修改角色成功");
        //同步添加数据权限
        sysRoleDeptService.saveOrUpdate(sysRole.getRoleId(), sysRole.getDeptIdList());
        //同步添加菜单权限
        System.out.println("修改数据权限成功");
        sysRoleMenuService.saveOrUpdate(sysRole.getRoleId(), sysRole.getMenuIdList());
        System.out.println("修改菜单权限成功");

        sysRoleDoorService.saveOrUpdate(sysRole.getRoleId(), sysRole.getDoorIdList());
        System.out.println("修改门户权限成功");
    }

    /**
     * 查询角色下面的用户
     *
     * @param role_id
     * @return
     */
    @Override
    public PageUtils roleuserlist(Long role_id, Map<String, Object> params) {

        List<Long> userId = sysUserRoleService.roleuserlist(role_id);
        if (userId.size() > 0) {
            params.put("userId", userId);
            PageUtils pageUtils = sysUserService.queryroleUserPage(params);
            return pageUtils;
        }


        return new PageUtils(null, 0, 0, 0);
    }

    /**
     * 文档添加角色权限时  初始化模糊查询
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryRoleListPage(Map<String, Object> params) {

        String lastname = (String) params.get("lastname_s");
        QueryWrapper<SysRoleEntity> wrapper = new QueryWrapper<>();
        wrapper.like("role_name", lastname).or().like("pin_yin_role_name", lastname);
        wrapper.apply(params.get(Constant.SQL_FILTER) != null, (String) params.get(Constant.SQL_FILTER));
        IPage<SysRoleEntity> page = this.page(
                new Query<SysRoleEntity>().getPage(params), wrapper
        );


        return new PageUtils(page);
    }


    /**
     * 获取字符串拼音的第一个字母
     *
     * @param chinese
     * @return
     */
    public static String toFirstChar(String chinese) {
        String pinyinStr = "";
        //转为单个字符
        char[] newChar = chinese.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (int i = 0; i < newChar.length; i++) {
            if (newChar[i] > 128) {
                try {
                    pinyinStr += PinyinHelper.toHanyuPinyinStringArray(newChar[i], defaultFormat)[0].charAt(0);
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } else {
                pinyinStr += newChar[i];
            }
        }
        return pinyinStr;
    }
}
